$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/coupon/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '优惠卷名称', name: 'name', index: 'name', width: 100 },
			{ label: '面额', name: 'denomination', index: 'denomination', width: 100,formatter: function(cellvalue, options, rowdata) {
			        var conditions = "";
			        if(rowdata.conditions == 0){
                        conditions = "无门槛";
                    }else{
                        conditions = "满"+rowdata.conditions+"元可用";
                    }
                    return "￥"+rowdata.denomination+"<br/>"+conditions;
                } },
			{ label: '有效期', name: 'conditions', index: 'conditions', width: 100,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.effectivedays == 0){
                        return rowdata.validitystar - rowdata.validityend;
                    }else{
                        return "领取当日"+rowdata.effectivedays+"天内有效";
                    }
                } },
			{ label: '剩余数量', name: 'count', index: 'count', width: 60 },
            { label: '已领取', name: 'receivenum', index: 'receivenum', width: 60 },
            { label: '已使用', name: 'usednum', index: 'usednum', width: 60 },
			{ label: '状态', name: 'statu', index: 'statu', width: 60,formatter: function(item, index) {
                    if (item === 0) {
                        return '进行中';
                    }
                    if (item === 1) {
                        return '已结束';
                    }
                    if (item === 2) {
                        return '已停用';
                    }
                } },
			{ label: '创建时间', name: 'createtime', index: 'createtime', width: 80 },
            { label: '操作', name: 'sy', width: 90,formatter: function(cellvalue, options, rowdata) {
                    var temp = "<a style='cursor:pointer;' onclick='vm.update("+ rowdata.id +")'>" +
                        "编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<a style='cursor:pointer;' onclick='vm.couponDetail("+ rowdata.id +")'>" +
                        "领取明细</a>&nbsp;&nbsp;<br/>" +
                        "<a style='cursor:pointer;' onclick='vm.del("+ rowdata.id +")'>" +
                        "推广</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    if(rowdata.statu==2){
                        return temp;
                    }else{
                        return temp + "<a style='cursor:pointer;' onclick='vm.stopUsed("+ rowdata.id +")'>停用</a>";
                    }
                }}

        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            name:null,
            statu:null,
            startime:null,
            endtime:null
		},
        qc:{
            wxname:null,
            statu:null,
            ordernum:null
        },
		showList: true,
		title: null,
		coupon: {},
        childShelves:[]
	},
	methods: {
		query: function () {
            vm.reload();
        },
        queryDetail: function () {
            vm.reloadDetail();
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.coupon = {};
            vm.coupon.type = 0;
            vm.childShelves = [];

            $("#yhjmc").removeAttr("readonly");
            $("#me").removeAttr("readonly");
            $("#ffsl").removeAttr("readonly");
            $("#mrxlsl").removeAttr("readonly");
            $("#gdrq").removeAttr("disabled");
            $("#lqdr").removeAttr("disabled");
            $("#wmk").removeAttr("disabled");
            $("#mj").removeAttr("disabled");
            $("#yxq").attr("readonly","readonly");
            $("#tj").attr("readonly","readonly");

            var bc = $("input:radio[name='conditions']");
            for(var i=0;i<bc.length;i++){
                if(bc[i].value == 0){
                    bc[i].checked = "checked";
                }else{
                    bc[i].checked = "";
                }
            }

            var bc = $("input:radio[name='effectivedays']");
            for(var i=0;i<bc.length;i++){
                if(bc[i].value == 0){
                    bc[i].checked = "checked";
                }else{
                    bc[i].checked = "";
                }
            }

            $("#shelves").html("");
            var temp ="<tr style='height:39px;'>" +
                "<td colspan='3' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择货架</td>" +
                "</tr>";

            $("#shelves").append(temp);

            var d = "<div style='width:46%;float:left;' class='input-group date'>" +
                "<input type='text' class='form-control' v-model='coupon.validitystar' id='kssj'>" +
                "<span class='input-group-addon' id='saddon'><i class='glyphicon glyphicon-th'></i></span></div>" +
                "<div  style='width: 4%;float:left;margin-left:7px;margin-top:8px;padding-left:1px;'>-</div>" +
                "<div style='width:48%;' class='input-group date'>" +
                "<input type='text' class='form-control' v-model='coupon.validityend' id='jssj'>" +
                "<span class='input-group-addon' id='eaddon'><i class='glyphicon glyphicon-th'></i></span></div>";
            $("#container").html(d);
            $("#container .input-group.date").datepicker({
                language: "zh-CN",
                clearBtn: true, //清除按钮
                format: "yyyy-mm-dd",
                todayHighlight:true
            });
		},
		update: function (id) {

			vm.showList = false;
            vm.title = "修改";
            vm.childShelves = [];
            
            vm.getInfo(id);
            $("#yhjmc").attr("readonly","readonly");
            $("#me").attr("readonly","readonly");
            $("#ffsl").attr("readonly","readonly");
            $("#mrxlsl").attr("readonly","readonly");
            $("#gdrq").attr("disabled","disabled");
            $("#lqdr").attr("disabled","disabled");
            $("#wmk").attr("disabled","disabled");
            $("#mj").attr("disabled","disabled");
            $("#yxq").attr("readonly","readonly");
            $("#tj").attr("readonly","readonly");
            var validitystar = "";
            if(vm.coupon.validitystar!=null){
                validitystar = vm.coupon.validitystar;
            }
            var validityend = "";
            if(vm.coupon.validityend!=null){
                validityend = vm.coupon.validityend;
            }
            var d = "<div style='width:46%;float:left;'>" +
                "<input type='text' class='form-control' id='kssj' readonly='readonly' value='"+validitystar+"' ></div>" +
                "<div style='width: 4%;float:left;margin-left:7px;margin-top:8px;padding-left:1px;'>-</div>" +
                "<div style='width:48%;float:left;'>" +
                "<input type='text' class='form-control' id='jssj' readonly='readonly' value ='"+validityend+"' ></div>";
            $("#container").html(d);

            if(vm.coupon.conditions !=0){
                var bc = $("input:radio[name='conditions']");
                for(var i=0;i<bc.length;i++){
                    if(bc[i].value == 1){
                        bc[i].checked = "checked";
                    }else{
                        bc[i].checked = "";
                    }
                }
            }

            if(vm.coupon.effectivedays !=0){
                var bc = $("input:radio[name='effectivedays']");
                for(var i=0;i<bc.length;i++){
                    if(bc[i].value == 1){
                        bc[i].checked = "checked";
                    }else{
                        bc[i].checked = "";
                    }
                }

            }else{
                vm.coupon.effectivedays = "";
            }

            var shelvesids = vm.coupon.shelvesid.split(",");

            var temp = "";
            $("#shelves").html("");
            for(var i=0;i<shelvesids.length;i++){
                var obj = {};
                $.ajax({
                    type: "POST",
                    async:false,
                    url: baseURL + "sys/goodshelves/info/"+shelvesids[i],
                    success: function(r){
                        obj.id = r.goodshelves.id;
                        obj.name = r.goodshelves.shelvesname;
                        obj.address = r.goodshelves.shelvesaddress;
                        vm.childShelves.push(obj);

                    }
                });
                temp +="<tr style='height:39px;' >" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].name+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].address+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[i].id+")' style='cursor: pointer'></td></tr>";
            }

            $("#shelvescount").text(vm.childShelves.length);
            $("#shelves").append(temp);

		},
        stopUsed: function (id) {

            vm.getInfo(id);
            console.log(vm.coupon)
            vm.coupon.statu = 2;
            $.ajax({
                type: "POST",
                url: baseURL + "sys/coupon/update",
                contentType: "application/json",
                data: JSON.stringify(vm.coupon),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getConditions: function(){
            var bc = $("input[name='conditions']:checked").val();

            if(bc == 0){
                $("#tj").attr("readonly","readonly");
            }
            if(bc == 1){
                $("#tj").removeAttr("readonly");
            }
        },
        getEffective: function(){
            var bc = $("input[name='effectivedays']:checked").val();

            if(bc == 0){
                $("#yxq").attr("readonly","readonly");
                $("#kssj").removeAttr("readonly");
                $("#jssj").removeAttr("readonly");
            }
            if(bc == 1){
                $("#yxq").removeAttr("readonly");
                $("#container").removeAttr("id");
                $("#kssj").attr("readonly","readonly");
                $("#jssj").attr("readonly","readonly");
            }
        },
        addShelves: function () {
            $("#jqGridAdd").jqGrid({
                url: baseURL + 'sys/goodshelves/list',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
                    { label: '货架名称', name: 'shelvesname', index: 'shelvesName', width: 170 },
                    { label: '货架地址', name: 'shelvesaddress', index: 'shelvesAddress', width: 225 },
                    { label: '货架分组', name: 'shelvesgroup', index: 'shelvesGroup',width: 170,formatter: function(cellvalue, options, rowdata) {
                            if(rowdata.shelvesgroup!=null&&rowdata.shelvesgroup!=""){
                                var groupname = "";
                                var arr = rowdata.shelvesgroup.split(",");
                                for(var i=0;i<arr.length;i++){
                                    $.ajax({
                                        type: "POST",
                                        async:false,
                                        url: baseURL + "sys/shelvesgroup/info/"+parseInt(arr[i]),
                                        success: function(r){
                                            groupname +=r.shelvesgroup.groupname;
                                            if(i !=arr.length-1){
                                                groupname +="/";
                                            }

                                        }
                                    });
                                }
                                return groupname;
                            }else{
                                return '未分组';
                            }


                        } }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerAdd",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridPagerAdd").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $('#myModal').modal();
        },
        couponDetail: function (id) {
            $("#jqGridAddCoupon").jqGrid({
                url: baseURL + 'sys/coupondetail/getlist',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
                    { label: '优惠券名称', name: 'couponid', index: 'couponid', width: 200 },
                    { label: '领取时间', name: 'createtime', index: 'createtime', width: 200 },
                    { label: '使用状态', name: 'statu', index: 'statu', width: 150,formatter: function(item, index) {
                            if (item === 0) {
                                return '未使用';
                            }
                            if (item === 1) {
                                return '已使用';
                            }
                            if (item === 2) {
                                return '已过期';
                            }
                        } },
                    { label: '使用时间', name: 'usetime', index: 'usetime', width: 200 },
                    { label: '领取人', name: 'userid', index: 'userid', width: 200 },
                    { label: '订单号', name: 'ordernum', index: 'orderNum', width: 200 }
                ],
                viewrecords: true,
                height: 385,
                rowNum: -1,
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                jsonReader : {
                    root: "list"
                },
                postData:{'id':id},
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridPagerAdd").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $("#couponid").val(id);
            $('#myCouponDetailModal').modal();
        },
        showShelves:function () {
            var grid = $("#jqGridAdd");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            var rows = grid.getGridParam("selarrrow");

            var temp = "";
            $("#shelves").html("");
            for(var i=0;i<rows.length;i++){
                var obj = {};
                var isExits = false;
                if(vm.childShelves.length>0){
                    for(var j=0;j<vm.childShelves.length;j++){
                        if(rows[i]==vm.childShelves[j].id){
                            isExits = true;
                        }
                    }
                    if(!isExits){
                        obj.id = rows[i];
                        obj.name = grid.getRowData(rows[i]).shelvesname;
                        obj.address = grid.getRowData(rows[i]).shelvesaddress;
                        vm.childShelves.push(obj);

                    }

                }else{
                    obj.id = rows[i];
                    obj.name = grid.getRowData(rows[i]).shelvesname;
                    obj.address = grid.getRowData(rows[i]).shelvesaddress;
                    vm.childShelves.push(obj);


                }

            }

            for(var k=0;k<vm.childShelves.length;k++){
                temp +="<tr style='height:39px;' >" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].name+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].address+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[k].id+")' style='cursor: pointer'></td></tr>";
            }
            $("#shelvescount").text(vm.childShelves.length);
            $("#shelves").append(temp);
            $('#myModal').modal("hide");

        },
        removeShelves: function (id) {
            var temp = "";
            $("#shelves").html("");
            var childShelvestemp = [];
            for(var i=0;i<vm.childShelves.length;i++){
                var obj = {};

                if(vm.childShelves[i].id !=id){
                    obj.id = vm.childShelves[i].id;
                    obj.name = vm.childShelves[i].name;
                    obj.address = vm.childShelves[i].address;
                    childShelvestemp.push(obj);

                    temp +="<tr style='height:39px;' >" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].name+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].address+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[i].id+")' style='cursor: pointer'></td></tr>";
                }

            }

            vm.childShelves = childShelvestemp;
            $("#shelvescount").text(vm.childShelves.length);
            if(vm.childShelves.length==0){
                temp +="<tr style='height:39px;'>" +
                    "<td colspan='3' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择货架</td>" +
                    "</tr>";
            }
            $("#shelves").append(temp);
        },
        changeStartTime:function(time) {
            console.log('starttime', time);
            this.coupon.validitystar = time;
        },
        changeEndTime:function(time) {
            console.log('starttime2', time);
            this.coupon.validityend = time;
        },
		saveOrUpdate: function (event) {
			var url = vm.coupon.id == null ? "sys/coupon/save" : "sys/coupon/update";
			if(vm.coupon.name =='' || typeof vm.coupon.name=='undefined'){
			    alert("优惠券名称不能为空");
            }else if(vm.coupon.denomination ==''|| typeof vm.coupon.denomination=='undefined'){
                alert("面额不能为空");
            }else if($('input:radio[name="conditions"]:checked').val() == ''){
                alert("优惠券面额不能为空");
            }else if(vm.coupon.count == '' ||typeof vm.coupon.count=='undefined'){
                alert("发放总量不能为空");
            }else if(vm.coupon.limitcount == '' ||typeof vm.coupon.limitcount=='undefined'){
                alert("每人限领不能为空");
            } else if(vm.childShelves.length ==0){
                alert("支持货架不能为空");
            }else{
			    var shelvesid = "";
                for(var i=0;i<vm.childShelves.length;i++){
                    shelvesid += vm.childShelves[i].id;
                    if(i!=vm.childShelves.length-1){
                        shelvesid += ",";
                    }
                }
                vm.coupon.shelvesid = shelvesid;
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.coupon),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                                vm.childShelves = [];
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }

		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/coupon/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/coupon/info/"+id,
                success: function(r){
                    vm.coupon = r.coupon;

                }
            });
		},
		reload: function (event) {
            var startime = $("#startime").val();
            var endtime = $("#endtime").val();
            if((startime!=''&&typeof startime!='undefined')&&(endtime!=''&&typeof endtime!='undefined')){
                var st = new Date(startime).getTime();
                var et = new Date(endtime).getTime();
                if(st>et){
                    alert("开始时间不能大于结束时间");
                    return;
                }
            }
			vm.showList = true;
            if(endtime!=''&&typeof endtime!='undefined'){
                var date = new Date(new Date(endtime).getTime()+(24*60*60*1000));
                var premonth   = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
                if(premonth<10){
                    premonth = "0"+premonth;
                }
                var preday = date.getDate(); //获取当前日(1-31)
                if(preday<10){
                    preday = "0"+preday;
                }
                endtime = date.getFullYear()+"-"+premonth+"-"+preday;
            }
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name':vm.q.name,'statu':vm.q.statu,'startime':startime,'endtime':endtime},
                page:page
            }).trigger("reloadGrid");
		},
        reloadDetail: function (event) {
            var startime = $("#start").val();
            var endtime = $("#end").val();
            var id = $("#couponid").val();
            if((startime!=''&&typeof startime!='undefined')&&(endtime!=''&&typeof endtime!='undefined')){
                var st = new Date(startime).getTime();
                var et = new Date(endtime).getTime();
                if(st>et){
                    alert("开始时间不能大于结束时间");
                    return;
                }
            }
            vm.showList = true;
            if(endtime!=''&&typeof endtime!='undefined'){
                var date = new Date(new Date(endtime).getTime()+(24*60*60*1000));
                var premonth   = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
                if(premonth<10){
                    premonth = "0"+premonth;
                }
                var preday = date.getDate(); //获取当前日(1-31)
                if(preday<10){
                    preday = "0"+preday;
                }
                endtime = date.getFullYear()+"-"+premonth+"-"+preday;
            }
            var page = $("#jqGridAddCoupon").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'id':id,'wxname':vm.qc.wxname,'number':vm.qc.ordernum,'statu':vm.qc.statu,'startime':startime,'endtime':endtime},
                page:page
            }).trigger("reloadGrid");
        }
	}
});